//
//  WBUserAccount.swift
//  传智微博
//
//  Created by zhoujiming on 2017/2/9.
//  Copyright © 2017年 gmcc. All rights reserved.
//

import UIKit

private let accoutFile : NSString = "userAccount.json"
/// 用户账户信息
class WBUserAccount: NSObject {
    
    
    /// 访问令牌
    var access_token : String? //= "2.00fEiw_CA3HTUD71ce9b46e11lQlIE"
    
    var uid : String?
    
    
    /// 过期日期（秒）
    var expires_in : TimeInterval = 0{
        didSet{
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    
    var expiresDate : Date?
    
    // 用户昵称
    var screen_name : String?
    
    var avatar_large : String?
    
    override var description: String{
        return yy_modelDescription()
    }
    
    override init() {
        super.init()
        // 从磁盘加载保存的文件
        guard let path = accoutFile.cz_appendDocumentDir(),
            let data = NSData(contentsOfFile: path),
        let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String:AnyObject] else{
                return
        }
        
        // 使用字典设置属性值
        yy_modelSet(with: dict ?? [:])
        
        // 判断token是否过期
        // expiresDate?.addingTimeInterval(<#T##timeInterval: TimeInterval##TimeInterval#>)
        if expiresDate?.compare(Date()) != .orderedDescending{
            print("账户过期")
            // 清空token
            access_token = nil
            uid = nil
            // 删除账户文件
            _ = try? FileManager.default.removeItem(atPath: path)
            
            return
        }
        print("账户正常")
        
        
    }
    /// 存储用户信息
    func saveAccount(){
        // 模型转字典
        var dict = (self.yy_modelToJSONObject() as? [String : AnyObject]) ?? [:]
        
        // 删除expires_in
        dict.removeValue(forKey: "expires_in")
        // 字典序列化
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),
            let filePath = accoutFile.cz_appendDocumentDir()
        else{
            return
        }
        // 写入磁盘
        (data as NSData).write(toFile: filePath, atomically: true)
        print("文件写入磁盘：\(filePath)")
        
    }
}
